'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IConfigUser, IDifference } from '@/interfaces';
import { updateUserConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { getDiffData, isNum } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateConfigUser({
  source,
  translatedFields,
}: {
  source: IConfigUser;
  translatedFields: PrefixedTTranslatedFields<'configAdminPage'>;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    rootId: string;
  }>({
    rootId: source.rootId ? source.rootId + '' : '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  useEffect(() => {
    const diffData = diff(
      {
        rootId: source.rootId ? source.rootId + '' : '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  const updateUserConfigMutation = useMutation(updateUserConfig);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const data = getDiffData(differenceData);
      await updateUserConfigMutation.mutateAsync({
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateUserConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function checkForm() {
    const { rootId } = form;

    if (!isNum(rootId)) {
      throw translatedFields.config.user.rootIdInvalidFormat;
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.config.user.rootId}
          </label>
          <input
            type="text"
            className="form-control"
            name="rootId"
            value={form.rootId}
            onChange={onChangeForm}
            aria-describedby="rootId"
          />
        </div>

        <button
          type="submit"
          disabled={updateUserConfigMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateUserConfigMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
